package com.pro01.backend.service;

import com.pro01.backend.dto.PostDetailDTO;
import com.pro01.backend.dto.PostSummaryDTO;
import com.pro01.backend.mapper.Forum2PostLikeMapper;
import com.pro01.backend.mapper.Forum2PostMapper;
import com.pro01.backend.pojo.Forum2Post;
import com.pro01.backend.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class Forum2PostService {

    @Autowired
    private Forum2PostMapper postMapper;
    @Autowired
    private PointService pointService;
    @Autowired
    private Forum2PostLikeMapper likeMapper;


    // 发帖
    public int createPost(Forum2Post post) {
//        int result = postMapper.insertPost(post);
//        // 发帖加积分
//        pointService.addPostReward(post.getUserId());
//        if (result == 0) {
//            throw new RuntimeException("发帖失败");
//        }
//        return result; // ✅ 返回插入结果
        int result = postMapper.insertPost(post);
        if (result == 0) {
            throw new RuntimeException("发帖失败");
        }
// 只有插入成功后才奖励积分
        pointService.addPostReward(post.getUserId());
        return result;
    }

    // 获取分页帖子
    public PageResult<PostSummaryDTO> getPostsBySection(String section, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<PostSummaryDTO> list = postMapper.selectPostsBySection(section, offset, pageSize);
        int total = postMapper.countPostsBySection(section);
        return new PageResult<>(total, list);
    }

    // 查看帖子详情
//    public PostDetailDTO getPostDetail(Long postId) {
//        postMapper.incrementViewCount(postId);
//        return postMapper.selectPostDetail(postId);
//    }
    public PostDetailDTO getPostDetail(Long postId, Long userId) {
        postMapper.incrementViewCount(postId);
        PostDetailDTO detail = postMapper.selectPostDetail(postId);
        if (detail != null) {
            boolean isLiked = likeMapper.hasUserLiked(userId, postId);
            detail.setIsLiked(isLiked);
        }
        return detail;
    }

    // 删除帖子
    public int deletePost(Long postId, Long userId, String role) {
        Long ownerId = postMapper.getPostOwnerId(postId);
        if (ownerId == null) {
            throw new RuntimeException("帖子不存在");
        }

        // 非管理员且不是本人，禁止删除
        if (!"ADMIN".equals(role) && !ownerId.equals(userId)) {
            throw new RuntimeException("无权限删除该帖子");
        }

        return postMapper.markPostAsDeleted(postId);
    }

    // 隐藏帖子
    public int hidePost(Long postId, Long userId, String role) {
        Long ownerId = postMapper.getPostOwnerId(postId);
        if (ownerId == null) {
            throw new RuntimeException("帖子不存在");
        }
        if (!"ADMIN".equals(role) && !ownerId.equals(userId)) {
            throw new RuntimeException("无权限隐藏该帖子");
        }
        return postMapper.updatePostStatus(postId, "HIDDEN");
    }

    // 取消隐藏帖子
    public int unhidePost(Long postId, Long userId, String role) {
        Long ownerId = postMapper.getPostOwnerId(postId);
        if (ownerId == null) {
            throw new RuntimeException("帖子不存在");
        }
        if (!"ADMIN".equals(role) && !ownerId.equals(userId)) {
            throw new RuntimeException("无权限显示该帖子");
        }
        return postMapper.updatePostStatus(postId, "ACTIVE");
    }

    // 模糊查询帖子
    public PageResult<PostSummaryDTO> searchPosts(String keyword, int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<PostSummaryDTO> list = postMapper.searchPostsByKeyword(keyword, offset, pageSize);
        int total = postMapper.countSearchPosts(keyword);
        return new PageResult<>(total, list);
    }

    // 推荐系统
    public Map<String, PostSummaryDTO> getRecommendedPosts() {
        List<PostSummaryDTO> list = postMapper.selectRecommendedPostPerSection();
        return list.stream().collect(Collectors.toMap(PostSummaryDTO::getSection, dto -> dto));
    }

    /**
     * 下面是管理员接口
     */
    // 查看所有帖子列表
    public PageResult<PostSummaryDTO> getAllPostsPaged(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<PostSummaryDTO> records = postMapper.selectAllPostsPaged(offset, pageSize);
        int total = postMapper.countAllPosts();
        return new PageResult<>(total, records);
    }

    // 删除任意帖子
    public int deletePostAsAdmin(Long postId) {
        return postMapper.markPostAsDeleted(postId);
    }

    // 隐藏/取消隐藏帖子
    public int setPostStatusAsAdmin(Long postId, String status) {
        return postMapper.updatePostStatus(postId, status);
    }

    // 置顶/取消置顶帖子
    public int setPostPinnedStatus(Long postId, boolean pinned) {
        return postMapper.updatePostPinned(postId, pinned);
    }

}
